package com.eudon.design_pattern.behavioral.observer.event_bus;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author eudon
 * @description 事件注册器
 * @date 2025/9/2
 * @email syd19970616@gmail.com
 * @address <a href="https://gitee.com/eudon">Gitee</a>
 */
public class EventRegister {
    private static final Map<Class<?>, List<EventAction>> eventActionMap = new HashMap<>();

    public static void registerObserver(Object observer) {
        Method[] methods = observer.getClass().getMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(Subscribe.class)) {
                if (method.getParameterCount() != 1) {
                    System.out.println("被Subscribe注解的方法参数只能存在一个");
                }
                Class<?> eventType = method.getParameterTypes()[0];
                eventActionMap.computeIfAbsent(eventType, k -> new ArrayList<>());
                eventActionMap.get(eventType).add(new EventAction(observer, method));
            }
        }
    }

    public static List<EventAction> getEventActions(Class<?> eventType) {
        return eventActionMap.get(eventType);
    }
}
